//
//  NetworkTools.swift
//  Swift网络访问
//
//  Created by Feng on 2017/6/6.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit
import AFNetworking


class NetworkTools: AFHTTPSessionManager {
    
    //网络请求类型枚举
    enum NetworkType {
        case get
        case post
    }
    
    //单例
    static let shareTools: NetworkTools =
    {
        let tool: NetworkTools = NetworkTools()
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    //MARK: --通用网络连接
    func loadData(networkType: NetworkType, URLString: String, parameters: Any?, resultCallBack: @escaping (_ responseObject: Any?, _ error: Error?) -> ())
    {
        if networkType == .get
        {
            get(URLString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                resultCallBack(responseObject,nil)
            }) { (_, error) in
                resultCallBack(nil,error)
            }
        }
        else
        {
            post(URLString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                resultCallBack(responseObject,nil)
            }, failure: { (_, error) in
                resultCallBack(nil,error)
            })
        }
    }
    
    //MARK: --获取access_token
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?) -> ())
    {
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let parameters: [String: Any] =
        [
            "client_id" : AppKey,
            "client_secret" : "e85093728d01018627f6a9376507f3c3",
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : Redirect_Uri
        ]
        
        //网络连接
        loadData(networkType: .post, URLString: urlStr, parameters: parameters, resultCallBack: callBack)
    }
    
    //MARK: --获取用户信息
    func requestUserInfo(access_token: String, uid:Int64, callBack: @escaping (Any?, Error?) -> ())
    {
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let parameters: [String: Any] =
        [
            "access_token": access_token,
            "uid": uid
        ]
        
        //网络连接
        loadData(networkType: .get, URLString: urlStr, parameters: parameters, resultCallBack: callBack)
    }
}

//MARK: --获取当前登录用户及其所关注（授权）用户的最新微博
extension NetworkTools
{
    func requestStatus(accessToken: String, maxId: Int64, sinceId:Int64, callBack: @escaping (Any?, Error?) -> ())
    {
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        print("\(urlStr)?access_token=\(accessToken)")
        print("----------")
        
        let parameters: [String: Any] =
        [
            "access_token": accessToken,
            "max_id": maxId,
            "since_id": sinceId
        ]
        
        //网络连接
        loadData(networkType: .get, URLString: urlStr, parameters: parameters, resultCallBack: callBack)
    }
}

//MARK: --发送一条微博
extension NetworkTools
{
    func sendMessage(access_token: String, status: String, callBack: @escaping (Any?, Error?) -> ())
    {
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters: [String: Any] =
        [
            "access_token": access_token,
            "status": status
        ]
        
        //网络连接
        loadData(networkType: .post, URLString: urlStr, parameters: parameters, resultCallBack: callBack)
    }
}

//MARK: --上传图片并发布一条新微博
extension NetworkTools
{
    func sendMessage(access_token: String, status: String, pic: UIImage, callBack: @escaping (Any?, Error?) -> ())
    {
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let parameters: [String: Any] =
        [
            "access_token": access_token,
            "status": status
        ]
        
        //  图片转成二进制，非常重要
        //        let imageData = UIImagePNGRepresentation(pic)!
        //  compressionQuality: 图片的质量系数0-1， 质量系统越大图片越清晰，图片就越大
        //  如果图片质量要求不高可以使用UIImageJPEGRepresentation
        let imageData = UIImageJPEGRepresentation(pic, 0.5)!

        //网络连接
        post(urlStr, parameters: parameters, constructingBodyWith: { (formData) in
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "feng", mimeType: "image/jpeg")
        }, progress: nil, success: { (_, response) in
            callBack(response,nil)
        }) { (_, error) in
            callBack(nil,error)
        }
    }
}
